package com.fang.algorithm.zuo.linked;

/**
 * @author fanglingxiao
 * @version 1.0
 * @description 单链表反转
 * @date 2022/4/23 12:28 上午
 **/
public class Test01_ReverseLinkedList {

    public static class Node {
        private int value;
        private Node next;

        public Node(int value) {
            this.value = value;
        }
    }

    public static void main(String[] args) {
        Node node1 = new Node(1);
        node1.next = new Node(2);
        node1.next.next = new Node(3);
        printNode(node1);
//        Node reverseNode = reverseLinkedList(node1);
        Node reverseNode = reverseLinkedList2(node1);
        printNode(reverseNode);
    }

    private static Node reverseLinkedList2(Node head) {
        // 1 -> 2 -> 3 -> null
        Node pre = null;
        Node next;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }


    public static Node reverseLinkedList(Node head) {
        Node pre = null;
        Node next = null;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }

    private static void printNode(Node reverseNode) {
        while (reverseNode != null) {
            System.out.print(reverseNode.value + "->");
            reverseNode = reverseNode.next;
        }
        System.out.println();
    }
}
